layui.define(['element','layer','form'], function (exports) {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form;

    //自定义验证
    form.verify({
        account: function (value, item) { //value：表单的值、item：表单的DOM对象
            if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                return '用户名不能有特殊字符';
            }
            if(/(^\_)|(\__)|(\_+$)/.test(value)){
                return '用户名首尾不能出现下划线\'_\'';
            }
            if(/^\d+\d+\d$/.test(value)){
                return '用户名不能全为数字';
            }
        },
        passWord: [/^[\S]{6,12}$/, '密码必须6到12位'],
        result_response: function (value) {
            var luo_res = $('#lc-captcha-response').val();
            if(luo_res.length < 1) {
                return '请点击人机识别认证';
            }
        }
    });

    // 监听登录并提交
    form.on('submit(login)', function (data) {
        var index = layer.load(1);
        $.ajax({
            url: "login",
            type: "post",
            dataType: "json",
            data: data.field,
            success:function (resp) {
                if(resp.code === 0) {
                    layer.close(index);
                    layer.msg(resp.message || "登录成功", { icon: 6 });
                    location.href = "index";
                } else {
                    LUOCAPTCHA.reset();
                    layer.close(index);
                    layer.msg(resp.message || "登录失败", { icon: 5 });
                }
            },
            error: function (outResult) {
                LUOCAPTCHA.reset();
                layer.close(index);
                layer.msg("请求异常", { icon: 2 });
            }
        });
        return false;
    });

    var adminLogin = {
        loginImport: function () {
            $.get('popup', {}, function (str) {
                layer.open({
                    id: 'layer-login',
                    type: 1,
                    title: false,
                    shade: 0.4,
                    shadeClose: true,
                    area: ['480px', '280px'],
                    closeBtn: 0,
                    anim: 1,
                    skin: 'pm-layer-login',
                    content: str
                });
                form.render('checkbox');
            });
        }
    };

    $('body').keydown(function (e) {
        if (e.keyCode == 13) {
            if ($('#layer-login').length <= 0) {
                adminLogin.loginImport();
            } else {
                $('button[lay-filter=login]').click();
            }
        }
    });

    exports('adminLogin',adminLogin);
});